<?php

namespace ZfcUser\Controller;

use Zend\Form\Form;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Stdlib\ResponseInterface as Response;
use Zend\Stdlib\Parameters;
use Zend\View\Model\ViewModel;
use ZfcUser\Service\User as UserService;
use ZfcUser\Model\EmailtokensTable;
use ZfcUser\Model\Emailtokens;
use ZfcUser\Model\TuserTable;
use ZfcUser\Model\Tuser;
use ZfcUser\Model\TcountryTable;
use ZfcUser\Model\Tcountry;
use ZfcUser\Model\TstateTable;
use ZfcUser\Model\Tstate;
use Zend\Authentication\AuthenticationService;
use SanAuthWithDbSaveHandler\Storage\IdentityManagerInterface;
use ZfcUser\Options\UserControllerOptionsInterface;
use Zend\View\Model\JsonModel;

class UserController extends AbstractActionController
{
    const ROUTE_CHANGEPASSWD = 'zfcuser/changepassword';
    const ROUTE_LOGIN        = 'auth';
    const ROUTE_REGISTER     = 'zfcuser/register';
    const ROUTE_CHANGEEMAIL  = 'zfcuser/changeemail';

    const CONTROLLER_NAME    = 'zfcuser';

    /**
     * @var UserService
     */
    protected $userService;

    /**
     * @var Form
     */
    protected $loginForm;

    /**
     * @var Form
     */
    protected $registerForm;

    /**
     * @var Form
     */
    protected $changePasswordForm;

    /**
     * @var Form
     */
    protected $changeEmailForm;

    /**
     * @todo Make this dynamic / translation-friendly
     * @var string
     */
    protected $failedLoginMessage = 'Authentication failed. Please try again.';

    /**
     * @var UserControllerOptionsInterface
     */
    protected $options;

    /**
     * User page
     */
	 protected $authService;
     
    //we will inject authService via factory
    protected $identityManager;

    //we will inject authService via factory
    public function indexAction()
    {
        if (!$this->zfcUserAuthentication()->hasIdentity()) {
            return $this->redirect()->toRoute(static::ROUTE_LOGIN);
        }
        return new ViewModel();
    }
	public function forgotPasswordAction()
    {
    	$message='';
		if(isset($_GET['success']) && $_GET['success']!='')
		{
			$message="Reset password link has been sended to given mail id";
		}
        return new ViewModel(array(
		'message'  => $message,
		)
		);
    }
	public function resetPasswordAction()
    {
		$request = $this->getRequest();
		//echo "<pre>";print_r(count($request->getPost()));exit;
		if(count($request->getPost()))
		{
			$post=$request->getPost();
			//echo "<pre>";print_r($request->getPost());exit;
			include('public/PHPMailer_5.2.4/sendmail.php');	
			$to=$post['fgtemail'];
			$regSubject="You are requested for reset password";
			$token='';
			$token = $this->getUniqueCode('10');
			$regMessage="<a href='user/reset-password?token=".$token."'>Click here to reset password</a>";
			if(sendMail($to,$regSubject,$regMessage)){
				$tokentable=$this->getServiceLocator()->get('ZfcUser\Model\EmailtokensTable');
				$tokentable->addToken($to,$token);
				return $this->redirect()->toUrl('forgot-password?success=1');
			}
		}
		else if(isset($_GET['token'])&& $_GET['token']!='')
		{
			$tokentable=$this->getServiceLocator()->get('ZfcUser\Model\EmailtokensTable');
            $tokendetails=$tokentable->getTokenDetails($_GET['token']);
			$tokendetail=array();
			if(count($tokendetails)){
			foreach($tokendetails as $details){
				$tokendetail=$details;
			}
			return new ViewModel(array(
					'tokendetail'=>$tokendetail,
					'error'=>0,
					)
				);
			}
			else
			{
				return new ViewModel(array(
					'tokendetail'=>$tokendetail,
					'error'=>1,
					)
				);
			}
		}else{
		return $this->redirect()->toUrl('/');
		}
		
    }
	public function getUniqueCode($length = "")
	{
		$code = md5(uniqid(rand(), true));
		if ($length != "")
		return substr($code, 0, $length);
		else
		return $code;
	}
    /**
     * Login form
     */
	public function homeAction(){
		return new ViewModel();
	}	
    public function loginAction()
    {
		if (isset($_POST['userEmail'])){
			$user=array();
			$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');
			$checkLogin = $table->checkLogin($_POST);			
			if($checkLogin!=""){				
				$_SESSION['user']['email']=$checkLogin->email_id;
				$_SESSION['user']['userId']=$checkLogin->user_id;			
				$result = new JsonModel(array(					
					'output' 		=> 'success',
				));	
			}else{				
				$result = new JsonModel(array(					
					'output' => 'notsuccess',
					'success'=>false,
				));
			}
			return $result;
		}else{
			return new ViewModel();
		}
	}
	
   
    /**
     * General-purpose authentication action
     */
    public function authenticateAction()
    {
        if ($this->zfcUserAuthentication()->getAuthService()->hasIdentity()) {
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }

        $adapter = $this->zfcUserAuthentication()->getAuthAdapter();
        $redirect = $this->params()->fromPost('redirect', $this->params()->fromQuery('redirect', false));

        $result = $adapter->prepareForAuthentication($this->getRequest());

        // Return early if an adapter returned a response
        if ($result instanceof Response) {
            return $result;
        }

        $auth = $this->zfcUserAuthentication()->getAuthService()->authenticate($adapter);

        if (!$auth->isValid()) {
            $this->flashMessenger()->setNamespace('zfcuser-login-form')->addMessage($this->failedLoginMessage);
            $adapter->resetAdapters();
            return $this->redirect()->toUrl($this->url()->fromRoute(static::ROUTE_LOGIN)
                . ($redirect ? '?redirect='. rawurlencode($redirect) : ''));
        }

        if ($this->getOptions()->getUseRedirectParameterIfPresent() && $redirect) {
            return $this->redirect()->toUrl($redirect);
        }

        return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
    }

    /**
     * Register new user
     */
	public function checkEmailAction()
	{	
		if(isset($_POST)){
			$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');
			$countemail = $table->checkEmail($_POST['email']);
			if($countemail != 0){
				$result = new JsonModel(array(					
					'output' => 'success',
				));	
			}else{
				$result = new JsonModel(array(					
					'output' => 'notsuccess',
				));	
			}
			return $result;
		}
	}
    public function registerAction()
    {
		if(isset($_POST['firstName'])){
			if($_POST['firstName']!=''){
				$token = $this->getUniqueCode('10');
				$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');
				$user = $table->addUser($_POST,$token);
				$tokentable=$this->getServiceLocator()->get('ZfcUser\Model\EmailtokensTable');
				$tokenId=$tokentable->addToken($user->email_id,$token);
				if(count($user)!=0){
					include('public/PHPMailer_5.2.4/sendmail.php');	
					$to=$user->email_id;
					$password=$user->password;
					$regSubject="You are requested for Account Activation";
					$regMessage="<a href='http://khanacadamy.local/user/change-password?id=".$user->user_id."&token=".$tokenId."'>Click here to Active Your Account</a>
								<p>Login Detailes</p>
								<p>Email: ".$to."</p>
								<p>PassWord: ".$token."</p>";
					if(sendMail($to,$regSubject,$regMessage)){
						$result = new JsonModel(array(					
							'output' => 'success',
						));	
					}else{
						$result = new JsonModel(array(					
							'output' => 'notsuccess',
						));	
					}
					return $result;
				}
			}else{
				$table = $this->getServiceLocator()->get('ZfcUser\Model\TcountryTable');
				$getcountries=$table->getallcountries();
				$table = $this->getServiceLocator()->get('ZfcUser\Model\TstateTable');
				$getstates=$table->getallstates();
				$table = $this->getServiceLocator()->get('ZfcUser\Model\TcitiesTable');
				$cities=$table->getallcities();
				$result = new ViewModel(array(					
					'country' => $getcountries,
					'states' => $getstates,
					'getcities' => $getcities,
				));
				return $result;
			}
		}else{
			$table = $this->getServiceLocator()->get('ZfcUser\Model\TcountryTable');
			$getcountries=$table->getallcountries();
			$table = $this->getServiceLocator()->get('ZfcUser\Model\TstateTable');
			$getstates=$table->getallstates();
			$table = $this->getServiceLocator()->get('ZfcUser\Model\TcitiesTable');
			$getcities=$table->getallcities();
			$result = new ViewModel(array(					
				'country' => $getcountries,
				'states' => $getstates,
				'cities' => $getcities,
			));
			return $result;
		}
    }

    /**
     * Change the users password
     */
    public function changePasswordAction()
    {
        if(isset($_GET['id'])){
			$token='';
			$status=array();
			$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');
			$user = $table->activeUser($_GET['id']);
			$tokentable=$this->getServiceLocator()->get('ZfcUser\Model\EmailtokensTable');
			$statuss = $tokentable->getTokenDetails($_GET['token']);
			foreach($statuss as $status){}
			if($status->status == 0){
				return $this->redirect()->toUrl('error-page-change-password');
			}else{
				$tokentable->addToken($_GET['token'],$token,0);
			}
		}else if(isset($_POST['userId'])){
			$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');
			$user = $table->changepwd($_POST['cnfpwrd'],$_POST['userId']);
		}
		return new ViewModel();				
	}
	public function errorPageChangePasswordAction(){
		return new ViewModel();
	}
	public function checkPasswordAction(){
		$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');
		$user = $table->getpassword($_POST['oldpasswrd'],$_POST['userId']);		
		if($user>0){			
			$result = new JsonModel(array(					
				'output' => 'success',
			));			
		}else{
			$result = new JsonModel(array(					
				'output' => 'not success',
			));
		}
		return $result;		
	}	
    public function changeEmailAction()
    {
        // if the user isn't logged in, we can't change email
        if (!$this->zfcUserAuthentication()->hasIdentity()) {
            // redirect to the login redirect route
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }

        $form = $this->getChangeEmailForm();
        $request = $this->getRequest();
        $request->getPost()->set('identity', $this->getUserService()->getAuthService()->getIdentity()->getEmail());

        $fm = $this->flashMessenger()->setNamespace('change-email')->getMessages();
        if (isset($fm[0])) {
            $status = $fm[0];
        } else {
            $status = null;
        }

        $prg = $this->prg(static::ROUTE_CHANGEEMAIL);
        if ($prg instanceof Response) {
            return $prg;
        } elseif ($prg === false) {
            return array(
                'status' => $status,
                'changeEmailForm' => $form,
            );
        }

        $form->setData($prg);

        if (!$form->isValid()) {
            return array(
                'status' => false,
                'changeEmailForm' => $form,
            );
        }

        $change = $this->getUserService()->changeEmail($prg);

        if (!$change) {
            $this->flashMessenger()->setNamespace('change-email')->addMessage(false);
            return array(
                'status' => false,
                'changeEmailForm' => $form,
            );
        }

        $this->flashMessenger()->setNamespace('change-email')->addMessage(true);
        return $this->redirect()->toRoute(static::ROUTE_CHANGEEMAIL);
    }

    /**
     * Getters/setters for DI stuff
     */

    public function getUserService()
    {
        if (!$this->userService) {
            $this->userService = $this->getServiceLocator()->get('zfcuser_user_service');
        }
        return $this->userService;
    }

    public function setUserService(UserService $userService)
    {
        $this->userService = $userService;
        return $this;
    }

    public function getRegisterForm()
    {
        if (!$this->registerForm) {
            $this->setRegisterForm($this->getServiceLocator()->get('zfcuser_register_form'));
        }
        return $this->registerForm;
    }

    public function setRegisterForm(Form $registerForm)
    {
        $this->registerForm = $registerForm;
    }

    public function getLoginForm()
    {
        if (!$this->loginForm) {
            $this->setLoginForm($this->getServiceLocator()->get('zfcuser_login_form'));
        }
        return $this->loginForm;
    }

    public function setLoginForm(Form $loginForm)
    {
        $this->loginForm = $loginForm;
        $fm = $this->flashMessenger()->setNamespace('zfcuser-login-form')->getMessages();
        if (isset($fm[0])) {
            $this->loginForm->setMessages(
                array('identity' => array($fm[0]))
            );
        }
        return $this;
    }

    public function getChangePasswordForm()
    {
        if (!$this->changePasswordForm) {
            $this->setChangePasswordForm($this->getServiceLocator()->get('zfcuser_change_password_form'));
        }
        return $this->changePasswordForm;
    }

    public function setChangePasswordForm(Form $changePasswordForm)
    {
        $this->changePasswordForm = $changePasswordForm;
        return $this;
    }

    /**
     * set options
     *
     * @param UserControllerOptionsInterface $options
     * @return UserController
     */
    public function setOptions(UserControllerOptionsInterface $options)
    {
        $this->options = $options;
        return $this;
    }

    /**
     * get options
     *
     * @return UserControllerOptionsInterface
     */
    public function getOptions()
    {
        if (!$this->options instanceof UserControllerOptionsInterface) {
            $this->setOptions($this->getServiceLocator()->get('zfcuser_module_options'));
        }
        return $this->options;
    }

    /**
     * Get changeEmailForm.
     *
     * @return changeEmailForm.
     */
    public function getChangeEmailForm()
    {
        if (!$this->changeEmailForm) {
            $this->setChangeEmailForm($this->getServiceLocator()->get('zfcuser_change_email_form'));
        }
        return $this->changeEmailForm;
    }

    /**
     * Set changeEmailForm.
     *
     * @param changeEmailForm the value to set.
     */
    public function setChangeEmailForm($changeEmailForm)
    {
        $this->changeEmailForm = $changeEmailForm;
        return $this;
    }
	public function statesoncitiesAction(){
		echo "<pre>";print_r($_POST);exit;
	}
	public function logoutAction(){	
		//echo "<pre>";print_r($_SESSION);exit;
		//unset($_SESSION['user']);
		return $this->redirect()->toUrl('login');
		
	}	
}
